package com.gdsz.libbasic.view

import android.content.Context
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import kotlin.math.ceil


abstract class BaseView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        setMeasuredDimension(
            measureWidth(widthMeasureSpec),
            measureHeight(heightMeasureSpec)
        )
    }

    protected var viewWidth: Int = 0
    protected var viewHeight: Int = 0
    private fun measureHeight(measureSpec: Int): Int {
        var result: Int
        val mode = MeasureSpec.getMode(measureSpec)
        val size = MeasureSpec.getSize(measureSpec)

        if (mode == MeasureSpec.EXACTLY) {
            result = size
        } else {
            result = defaultLayoutHeight()
            if (mode == MeasureSpec.AT_MOST) {
                result = result.coerceAtMost(size)

            }
        }
        viewHeight = result

        return result
    }

    private fun measureWidth(measureSpec: Int): Int {
        var result: Int
        val mode = MeasureSpec.getMode(measureSpec)
        val size = MeasureSpec.getSize(measureSpec)

        if (mode == MeasureSpec.EXACTLY) {
            result = size
        } else {
            result = defaultLayoutWidth()
            if (mode == MeasureSpec.AT_MOST) {
                result = result.coerceAtMost(size)

            }
        }
        viewWidth = result

        return result
    }

    open fun defaultLayoutHeight(): Int {
        return 0
    }

    open fun defaultLayoutWidth(): Int {
        return 0
    }

    /**
     * 获取字体高
     * @param mPaint Paint
     * @return Int
     */
    protected fun getTxtHeight(mPaint: Paint): Int {
        val fm = mPaint.fontMetrics
        return ceil((fm.descent - fm.ascent).toDouble()).toInt()
    }


}